package com.javaframe.role.security.intercept;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.SecurityConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.rowset.SqlRowSet;

public class RdbmsFilterInvocationDefinition extends JdbcDaoSupport {
	
	private static final Log logger = LogFactory
			.getLog(RdbmsFilterInvocationDefinition.class);

	private String loadUrlRoleMappingQuery = "select ro.rolename,ul.* from resource re,resource_role rr, role ro ,urls ul, url_permissions up  where ro.roleid = rr.role_id and rr.resource_id = re.resource_id and re.resource_id =up.resource_id  and up.url_id =ul.url_id";
	
	public RdbmsFilterInvocationDefinition() {
	}

	public RdbmsFilterInvocationDefinition(DataSource dataSource) {
		this.setDataSource(dataSource);
	}

	public List<RdbmsEntryHolder> execute() {
		if (logger.isDebugEnabled()) {
			logger.debug("Extract web authorities infomation from database...");
		}

		SqlRowSet rs = getJdbcTemplate()
				.queryForRowSet(loadUrlRoleMappingQuery);

		Map<String, ConfigAttributeDefinition> map = new HashMap<String, ConfigAttributeDefinition>();
		while (rs.next()) {
			String url = rs.getString("url").trim();
			String role = rs.getString("rolename").trim();
			if (map.keySet().contains(url)) {
				ConfigAttributeDefinition configAttributeDefinition = map
						.get(url);
				configAttributeDefinition
						.addConfigAttribute(new SecurityConfig(role));
				map.put(url, configAttributeDefinition);
			} else {
				ConfigAttributeDefinition configAttributeDefinition = new ConfigAttributeDefinition();
				configAttributeDefinition
						.addConfigAttribute(new SecurityConfig(role));
				map.put(url, configAttributeDefinition);
			}
		}
		List<RdbmsEntryHolder> list = new ArrayList<RdbmsEntryHolder>();
		Iterator<String> ite = map.keySet().iterator();
		while (ite.hasNext()) {
			String url = ite.next();
			RdbmsEntryHolder holder = new RdbmsEntryHolder(url, map.get(url));
			list.add(holder);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("RdbmsEntryHolder list size: " + list.size());
		}
		return list;
	}

}
